#!/usr/bin/python2.5
# Copyright 2009 Joe LaPenna
"""Main entrypoint for the dumpcatcher backend."""

import logging

import wsgiref.handlers

from google.appengine.ext import webapp

from endpoints import crash
from endpoints import product
from endpoints import user


# Set the app to debug mode.
DEBUG = False


def RedirectHandlerGenerator(target):
  """Redirect a request to another url, target."""
  TARGET = target
  class RedirectHandler(webapp.RequestHandler):
    def get(self):
      logging.debug('Redirecting %s -> %s', self.request.url, TARGET)
      self.redirect(TARGET)
  return RedirectHandler


def create_application():
  """Create the application that will be run in main."""
  logging.debug('Create Application called')
  application = webapp.WSGIApplication(
      [
          ('/', RedirectHandlerGenerator('/user')),
          #('/add', crash.Add),
          ('/user', user.User),
          ('/product/.+', product.Product),
          ('/product_add', product.Add),
          ('/product_delete', product.Delete),
          ('/product_delete_task', product.DeleteTask),
      ],
      debug=DEBUG)
  return application


# -- Main entry point (two methods for profiling). -- #

def profile_main():
  """From http://code.google.com/appengine/kb/commontasks.html"""
  logging.debug('DEBUG Main Being Used')
  # This is the main function for profiling
  # We've renamed our original main() to real_main()
  import cProfile, pstats
  prof = cProfile.Profile()
  prof = prof.runctx("real_main()", globals(), locals())
  print "<div class=\"debug\"><pre>"
  stats = pstats.Stats(prof)
  stats.sort_stats("time")  # Or cumulative
  stats.print_stats(80)  # 80 = how many to print
  # The rest is optional.
  # stats.print_callees()
  # stats.print_callers()
  print "</pre></div>"


def real_main():
  """Hide the real main method so that we can run profiling."""
  logging.debug('Real Main Being Used')
  wsgiref.handlers.CGIHandler().run(create_application())


def set_main():
  """Set __module__.main to either the real or debugging main.

  Uses global "DEBUG"
  """
  logging.debug('Setting main()')
  global main
  if DEBUG:
    main = profile_main
  else:
    main = real_main


# this needs to be executed at the module level or main() will not be cached by
# GAE.
set_main()


if __name__ == '__main__':
  main()
